﻿using InternetSpiderLib;
using System;
using System.Collections.Generic;
using System.Text;
using WeChatGZHTextExtractor.Tools;

namespace WeChatGZHTextExtractor.BusinessCreaters
{
    public class BC_DownloadImage : IBusinessCreater
    {
        private SceneManager _SceneManager;

        public BC_DownloadImage()
        {
            _SceneManager = SingleCase.Get<SceneManager>();
        }

        public Action Create()
        {
            if (!ImageUrlMonitoringQueue.GetInstance().TryPop(out DataBox data))
                return null;

            return () =>
            {
                var url = data.Get<string>(PublicKey.HtmlInfo.URL);
                var base_url = data.Get<string>(PublicKey.HtmlInfo.REFERENCE_URL);

                LogHelper.GetInstance().Log(LogType.Info, url);

                var file_name = SaveFileHelper.GetSaveFullPath(HttpHelper.NewLocalFileName(url));
                HttpHelper.CreateParentDir(file_name);
                HttpHelper.HttpDownload(url, base_url, file_name);

                _SceneManager.TriggerScene(new DataBox(data)
                    .Set<string>(PublicKey.EventType.EVENT_NAME, PublicKey.EventType.IMAGE_DOWNLOAD)
                    .Set<string>(PublicKey.HtmlInfo.FILE_SAVE_NAME, file_name));
            };
        }
    }
}
